import { Context } from "egg";

/**
 * 日志中间件
 * 统一记录所有接口的请求和响应日志
 */
export default function loggerMiddleware() {
  return async (ctx: Context, next: () => Promise<any>) => {
    const startTime = Date.now();
    const requestId = ctx.reqId || generateRequestId();

    // 记录请求开始日志
    ctx.logger.info("[REQUEST] 接口请求开始", {
      requestId,
      method: ctx.method,
      url: ctx.url,
      ip: ctx.ip,
      userAgent: ctx.get("User-Agent"),
      contentType: ctx.get("Content-Type"),
      sessionId: ctx.session?.sessionId,
      userId: ctx.session?.userId,
      username: ctx.session?.username,
      timestamp: new Date().toISOString()
    });

    try {
      await next();

      const duration = Date.now() - startTime;

      // 记录请求成功日志
      ctx.logger.info("[RESPONSE] 接口请求完成", {
        requestId,
        method: ctx.method,
        url: ctx.url,
        ip: ctx.ip,
        status: ctx.status,
        duration: `${duration}ms`,
        responseSize: getResponseSize(ctx.body),
        timestamp: new Date().toISOString()
      });
    } catch (error) {
      const duration = Date.now() - startTime;

      // 记录请求错误日志
      ctx.logger.error("[ERROR] 接口请求异常", {
        requestId,
        method: ctx.method,
        url: ctx.url,
        ip: ctx.ip,
        status: ctx.status,
        duration: `${duration}ms`,
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined,
        timestamp: new Date().toISOString()
      });

      throw error;
    }
  };
}

/**
 * 生成请求ID
 */
function generateRequestId(): string {
  return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

/**
 * 获取响应体大小
 */
function getResponseSize(body: any): string {
  if (!body) return "0B";

  try {
    const size = JSON.stringify(body).length;
    if (size < 1024) return `${size}B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)}KB`;
    return `${(size / 1024 / 1024).toFixed(2)}MB`;
  } catch {
    return "unknown";
  }
}
